package com.heima.user.service.impl;

import com.heima.common.constants.BehaviorContstants;
import com.heima.common.redis.CacheService;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.UserRelationDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.user.service.IApUserRelationService;
import com.heima.utils.thread.AppThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

@Slf4j
@Service
@Transactional
public class ApUserRelationServiceImpl implements IApUserRelationService {

    @Resource
    private CacheService cacheService;

    /**
     * 用户关注|取消关注
     * <p>
     * 用户关注作者 ，用户是作者粉丝
     * <p>
     * 保存用户关注的作者，保存作者的粉丝用户
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult follow(UserRelationDto dto) {
        ApUser user = AppThreadLocalUtil.getUser();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        if (dto.getOperation() == 0) {
            /**
             * 保存用户关注的作者ID
             */
            cacheService.zAdd(BehaviorContstants.APUSER_FOLLOW_RELATION + user.getId(), String.valueOf(dto.getAuthorId()), System.currentTimeMillis());

            /**
             * 保存关注作者的粉丝ID
             */
            cacheService.zAdd(BehaviorContstants.APUSER_FANS_RELATION + dto.getAuthorId(), user.getId().toString(), System.currentTimeMillis());

        } else {
            /**
             * 用户关注作者列表去除该作者
             */
            cacheService.zRemove(BehaviorContstants.APUSER_FOLLOW_RELATION + user.getId(), String.valueOf(dto.getAuthorId()));

            /**
             * 作者粉丝列表去除用户
             */
            cacheService.zRemove(BehaviorContstants.APUSER_FANS_RELATION + dto.getAuthorId(), user.getId().toString());
        }
        return ResponseResult.okResult(null);
    }
}
